<template>
  <div>
    <!--导航栏-->
    <van-nav-bar
      title="考勤"
      left-text="返回"
      right-text="按钮"
      left-arrow
      :fixed="true"
      @click-left="onClickLeft"
    />

    <!--标签栏-->
    <van-tabs v-model="active">
      <van-tab title="内勤打卡">
        <!--  <van-button square type="primary">方形按钮</van-button>
          <van-button round type="info">圆形按钮</van-button>-->
        <div @click="startInerWork">
          <div>
            <div class="radius">
              <div class="boxCtl">
                <div class="boxBtn">
                  <span class="boxBtn2">点击打卡</span>
                  <p class="timeME">{{courentTime}}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-tab>
      <van-tab title="外勤打卡">
        <div @click="startOutWork">
          <div>
            <div class="radius">
              <div class="boxCtl">
                <div class="boxBtn">
                  <span class="boxBtn2">点击打卡</span>
                  <p class="timeME">{{courentTime}}</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!--  <div>
            &lt;!&ndash;地图区域&ndash;&gt;
            <div class="mapBox" id="mapBox" style="width: 60%;height: 200px;">
            </div>

          </div>-->
        <van-button type="info" @click="getMyPosition">查看当前位置</van-button>
        <p>当前位置：{{courentLopction}}</p>
        <h4 id='status'></h4>
        <hr>
        <p id='result'></p>
        <hr>
        <div class="mapBox" id="mapBox" style="width: 100%;height: 40vh;">
        </div>

      </van-tab>
      <van-tab title="考勤统计">
        <!--时间筛选-->
        <div class="timeCtl">
          <van-row type="flex">
            <van-col span="6">
              <van-button type="primary">月</van-button>
            </van-col>
            <van-col span="6">
              <van-button type="primary">周</van-button>
            </van-col>
          </van-row>
        </div>
        <!-- 左对齐 -->
        <div>
          <van-cell-group>
            <van-cell title="平均工时" value="内容">
              7.5小时
            </van-cell>
            <van-cell title="出勤天数" value="内容">
              7天
            </van-cell>
            <van-cell title="休息天数" value="内容">
              10天
            </van-cell>
            <van-cell title="迟到" value="内容">
              7次
            </van-cell>
            <van-cell title="早退" value="内容">
              7次
            </van-cell>
            <van-cell title="外勤" value="内容">
              7次
            </van-cell>
            <van-cell title="加班" value="内容">
              7次
            </van-cell>
          </van-cell-group>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
  import {Toast} from 'vant';
  import {location} from "@/components/location";
  import Attendance from "@/api/Attendance";
  export default {
    data() {
      return {
        active: 0,
        courentTime:'',
        courentLopction:''
      };
    },
    /*  beforeMount() {
        require(["https://webapi.amap.com/maps?v=1.4.9&key=ed863c1b5d69c3782397336031be2039"
          ], () => {
          setTimeout(() => {
          }, 1500);
        }
      )
      },*/
    created() {
      // this.getLocation(); // 调用获取地理位置
    },
    mounted(){
      let _this = this; // 声明一个变量指向Vue实例this，保证作用域一致
      this.timer = setInterval(() => {
        _this.courentTime =this.getTime(); // 修改数据date
      }, 1000)
    },
    methods: {
      //时间处理
      getCourentTime(){
        this.courentTime = new Date()
      },
      getTime(){
        var date1=new Date();
        var hours=date1.getHours();
        var minutes=date1.getMinutes();
        var seconds=date1.getSeconds();
        return hours+":"+minutes+":"+seconds
      },
      onClickLeft() {
        this.$router.push('/work')
      },
      onClickRight() {
        Toast('按钮');
      },
     //内勤打卡
      startInerWork() {
        const toast1 = Toast.loading({
          message: '定位中...',
          forbidClick: true
        });

        this.getMyPosition();

        Attendance.insertAttendance({
          clockType:1,//考勤类型（1：内勤打卡，2：外勤打卡）
          userId: this.$store.getters.userInfo.userId,
          nickName: this.$store.getters.userInfo.nickName,
          clockAddress:this.courentLopction
        })
          .then(res => {
            // 返回数据
            // toast1.clear();
            Toast.success("打卡成功");
          })
          .catch(err => {
            // 异常情况
            Toast.success("打卡异常");
          })

      },
      //外打卡
      startOutWork() {
        const toast1 = Toast.loading({
          message: '定位中...',
          forbidClick: true
        });

        this.getMyPosition();

        Attendance.insertAttendance({
          clockType:2,//考勤类型（1：内勤打卡，2：外勤打卡）
          userId: this.$store.getters.userInfo.userId,
          nickName: this.$store.getters.userInfo.nickName,
          clockAddress:this.courentLopction
        })
          .then(res => {
            // 返回数据
            // toast1.clear();
            Toast.success("打卡成功");
          })
          .catch(err => {
            // 异常情况
            Toast.success("打卡异常");
          })
      },


      /**获取地图定位*/
      getMyPosition() {

        var mapObj = new AMap.Map('mapBox', {
          resizeEnable: true
        });

        const self = this;
        AMap.plugin('AMap.Geolocation', function() {
          var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
            // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
            buttonOffset: new AMap.Pixel(10, 20),
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            zoomToAccuracy: true,
            //  定位按钮的排放位置,  RB表示右下
            buttonPosition: 'RB'
          })

          geolocation.getCurrentPosition()
          AMap.event.addListener(geolocation, 'complete', onComplete)
          AMap.event.addListener(geolocation, 'error', onError)

          function onComplete (data) {
            // data是具体的定位信息

            if (data){
              console.log('位置信息位置：', data)
              console.log('定位成功，当前位置：', data.formattedAddress)
              self.courentLopction = data.formattedAddress;
            }

          }

          function onError (data) {
            // 定位出错
            console.log('定位失败错误：', data);
            self.getLngLatLocation()
          }
        })
       },

      getLngLatLocation() {
        AMap.plugin('AMap.CitySearch', function () {
          var citySearch = new AMap.CitySearch()
          citySearch.getLocalCity(function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              // 查询成功，result即为当前所在城市信息
              console.log('通过ip获取当前城市：', result)
              //逆向地理编码
              AMap.plugin('AMap.Geocoder', function () {
                var geocoder = new AMap.Geocoder({
                  // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                  city: result.adcode
                })

                // var lnglat = [116.396574, 39.992706]
                // var lnglat = [118.781661,31.997589]//当前坐标
                // var lnglat = [118.781661,31.80452471]//当前坐标
                // rectangle: "118.4253323,31.80452471;119.050169,32.39401346"
                var lnglat = result.rectangle.split(';')[0].split(',');
                console.log(lnglat);

                geocoder.getAddress(lnglat, function (status, data) {
                  if (status === 'complete' && data.info === 'OK') {
                    // result为对应的地理位置详细信息
                    console.log(data)
                    if (data){
                      // this.courentLopction = data;
                      this.courentLopction = data.formattedAddress;
                    }
                  }
                })
              })
            }
          })
        })
      }
    },
    beforeDestroy() {
      if (this.timer) {
        clearInterval(this.timer); // 在Vue实例销毁前，清除我们的定时器
      }
    }

  }
</script>

<style scoped>
  .radius {
    width: 150px;
    height: 150px;
    border-radius: 50%;
    border: none;
    margin: 20% auto;
    background-color: #1994ff;

  }

  .boxBtn2 {
    background-color: #1994ff;
    border: none;
    color: white;
  }

  .boxCtl {
    position: relative;
  }

  .boxBtn {
    position: absolute;
    top: 75px;
    left: 50%;
    transform: translate(-50%, -50%);

  }

  .timeME {
    margin-top: 10%;
    color: black;
    font-weight: bold;
    font-size: 18px;
  }

  .timeCtl {
    margin-right: 60%;
  }

</style>
